package com.cheyun.netsalev3.view.orderlist

import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.PopupWindow
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.HomePageAdapter
import com.cheyun.netsalev3.databinding.ActivityOrderListBinding
import com.cheyun.netsalev3.databinding.OrderlistPopItemBinding
import com.cheyun.netsalev3.utils.BaseActivity
import com.cheyun.netsalev3.utils.CommonFunc
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.InjectorUtils
import com.cheyun.netsalev3.viewmodel.orderlist.OrderListFragmentViewModel
import com.google.android.material.tabs.TabLayout


class OrderListActivity : BaseActivity<ActivityOrderListBinding>() {


    override fun initContentView(): Int {
        return R.layout.activity_order_list
    }

    var titles = arrayListOf("已到店", "未到店")
    var nkeys = arrayListOf("1","0")
    var popupWindow: PopupWindow? = null

    private var searchMap = HashMap<String, String>()

    private var listFragmet = ArrayList<Fragment>()
    override fun initViewModel(): ViewModel? {
        val factory = InjectorUtils.getOrderListViewModelFactory(nkeys,searchMap)
        return ViewModelProviders.of(this, factory).get(OrderListFragmentViewModel::class.java)
    }

    override fun initData() {
    }

    override fun initView() {
        for (i in titles.indices) {
            listFragmet.add(OrderListFragment.newInstance(nkeys[i]))
        }
        val pagerAdapter = HomePageAdapter(supportFragmentManager, listFragmet)
        pagerAdapter.titles = titles
        binding.viewPager.offscreenPageLimit = 3
        binding.viewPager.adapter = pagerAdapter
        binding.tabLayout.setupWithViewPager(binding.viewPager)
        //选中的位置
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(p0: TabLayout.Tab?) {

            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                var pos = binding.tabLayout.selectedTabPosition
                var nke = nkeys[pos]
                binding.viewModel?.totlelist!![nke]?.observe(this@OrderListActivity, Observer {
                    binding.totleText.text = titles[pos] + it.toString() + "人"
                    showTips()
                })
            }
        })
        var nke = nkeys[0]
        binding.viewModel?.totlelist!![nke]?.observe(this@OrderListActivity, Observer {
            binding.totleText.text = titles[0] + it.toString() + "人"
            showTips()
        })
        binding.searchBut.setOnClickListener {
            showPop(it)

        }
        binding.searchText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                //关闭软键盘
                closeKeyword()
                //do something
                //doSearch();
                searchMap = HashMap<String, String>()
                searchMap["keyword"] = binding.searchText.text.toString()

                refresh()
                true
            } else
                false
        }
        binding.leftBut.setOnClickListener{
            finish()
        }
    }

    fun closeKeyword(){
        val view = window.peekDecorView()
        if (view != null) {
            val inputmanger = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputmanger.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    fun refresh(){
        var hashMap = HashMap<String, String>()

        searchMap.forEach {
            hashMap[it.key] = it.value
        }
        for (fragment in listFragmet) {
            (fragment as OrderListFragment).setSearch(hashMap)
        }
    }

    private fun showTips(){
        binding.totleText.setVisibility(View.VISIBLE)
        binding.totleText.clearAnimation()
        val animation = AlphaAnimation(1f, 0f)
        animation.duration = 3000
        binding.totleText.startAnimation(animation)
        binding.totleText.setVisibility(View.GONE)
    }

    /**
     * 显示弹窗
     */
    private fun showPop(view: View) {
        if (popupWindow == null) {
            var popbingding =
                    DataBindingUtil.inflate<OrderlistPopItemBinding>(LayoutInflater.from(this),
                            R.layout.orderlist_pop_item, null, false)
            popupWindow = PopupWindow(popbingding.root,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT)
            popbingding.btnToday.setOnClickListener {
                searchMap = HashMap<String, String>()
                var d = CommonFunc.getPastDate(0)
                searchMap["darrivetime"] = d + ","+d
                popupWindow!!.dismiss()
                refresh()
            }
            popbingding.btnTomorrow.setOnClickListener {
                var d = CommonFunc.getPastDate(-1)
                searchMap["darrivetime"] = d + ","+d
                popupWindow!!.dismiss()
                refresh()
            }
//            popbingding.btnConfirm.setOnClickListener {
//
//                popupWindow!!.dismiss()
//            }
//            popbingding.btnUnConfirm.setOnClickListener {
//
//                popupWindow!!.dismiss()
//            }
        }
        popupWindow?.isOutsideTouchable = true
        this?.apply {
            popupWindow?.showAsDropDown(view, FunctionUtils.dip2px(this, -10f), -10, Gravity.BOTTOM)
        }
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        if (resultCode == 101) {
//            var list = data?.getSerializableExtra("poplist") as List<CustomListParam>
//            binding.viewModel?.onResult(list)
//            for (fragment in listFragmet) {
//                fragment?.onActivityResult(requestCode, resultCode, data)
//            }
//            Log.e("101....", list.toString())
//        }
//    }

}
